<?php

class Ext_Controller_Plugin_Layout extends Zend_Controller_Plugin_Abstract 
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $module = $request->getModuleName();
 
        $front = Zend_Controller_Front::getInstance();
        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        $bootstrap->bootstrap('view');
        $view = $bootstrap->getResource('view');
        
        /*
         * $moduleParams = $view->$module;
        $bootstrap->bootstrap('frontController');
        $frontController = $bootstrap->getResource('frontController');
        $frontController->setParam('noViewRenderer', true);
        */
        
        $settings = Zend_Registry::get('settings');
        $theme = $settings['defaultTheme'];
        
        $view->settings = $settings;
        
        $view
            ->addBasePath(APPLICATION_PATH . '/views/default/modules/' . $module . '/')
            ->addScriptPath(APPLICATION_PATH . '/views/default/scripts/')
            ->addScriptPath(APPLICATION_PATH . '/views/default/layouts/')
            ->addScriptPath(APPLICATION_PATH . '/views/default/modules/' . $module . '/layouts/')
            ->addHelperPath(LIBRARY_PATH . '/Ext/View/Helper/', 'Ext_View_Helper')
            ;

        if($theme != "default"){
            $view
                ->addBasePath(APPLICATION_PATH . '/views/'. $theme. '/modules/' . $module . '/')
                ->addScriptPath(APPLICATION_PATH . '/views/'. $theme. '/scripts/')
                ->addScriptPath(APPLICATION_PATH . '/views/'. $theme. '/layouts/')
                ->addScriptPath(APPLICATION_PATH . '/views/'. $theme. '/modules/' . $module . '/layouts/')
                ;
        }
        
        $layout = Zend_Layout::getMvcInstance();
        if($module == 'admin'){
            $layout->setLayout('layout_admin');
        }else{
            $layout->setLayout('layout_default');
        }
    }
        
    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        $bootstrap->bootstrap('view');
        $view = $bootstrap->getResource('view');
        if(isset($view->messages)){
            $response = Zend_Controller_Front::getInstance()->getResponse();
            $response->insert('messages', $view->render('script_messages.phtml'));
        }
        
        if(isset($view->paginator)){
            $view->requestParams  = $request->getParams();
        }else{
            $view->requestParams  = array();
        }
    }
}